import { ReportHistoriesComponent } from './../../@shared/components/report-histories/report-histories.component';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { PausedComponent } from './../paused/paused.component';
import { DialogService } from 'ng-devui';
import { JobOrderService } from 'src/app/@core/services/jobOrder/job-order.service';
import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FooterItems } from 'src/app/@core/data/job';
import { DirctoryService } from 'src/app/@core/services/dirctory/dirctory.service';
@Component({
  selector: 'app-opterator-task-datail',
  templateUrl: './opterator-task-datail.component.html',
  styleUrls: ['./opterator-task-datail.component.scss'],
})
export class OpteratorTaskDatailComponent {
  item: any = {};
  now: any;
  note: any = '';
  msgs: Array<Object> = [];
  radioItems = ['工序流转', '入库'];
  currentSelectedItem = '工序流转';
  selectedFooterItem = FooterItems.TaskList;
  footerItems: FooterItems[] = Object.values(FooterItems);
  keyboardItems = [
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '.',
    '0',
    'del',
  ];
  numberItems = [
    { num: 0, text: '计划数', color: 'default' },
    { num: 0, text: '已报工数', color: 'default' },
    { num: 0, text: '剩余数', color: 'default' },
    { num: 0, text: '可报工数', color: 'default' },
    { num: 0, text: '合格数', color: 'rgb(0, 208, 143)' },
    { num: 0, text: '不合格数', color: 'rgb(255, 65, 54)' },
    { num: 0, text: '报废数', color: 'rgb(255, 134, 32)' },
    { num: 0, text: '维修中', color: 'rgb(163, 167, 179)' },
  ];
  employeeCode: any;
  jobOrderProcessId: any;
  pendingInspectionQuantity: any = null;
  productionInspectionOrderNum: string = '';
  constructor(
    private route: ActivatedRoute,
    private JobOrderService: JobOrderService,
    private router: Router,
    private DialogService: DialogService,
    private DirctoryService: DirctoryService,
    private EncodeRulesService: EncodeRulesService
  ) {
    this.employeeCode = JSON.parse(
      localStorage.getItem('userinfo')
    ).employeeCode;
  }
  allUnits: any = [];
  isStart: any;
  isFinished: any;
  reportedAmount: any = null;
  unqualifiedAmount: any = null;
  scrapAmount: any = null;
  selectedInput: string = 'reportedAmount';
  jobOrderNum: any;
  processNum: any;
  userName: any;
  inspectionInputDisabled: boolean = false;
  normalInputDisabled: boolean = false;
  ngOnInit(): void {
    this.userName = JSON.parse(localStorage.getItem('userinfo')).username;
    setInterval(() => {
      this.now = new Date();
    }, 1000);
    this.route.queryParams.subscribe((params) => {
      this.jobOrderProcessId = params.jobOrderProcessId;
      this.processNum = params.processNum;
      this.JobOrderService.GetJobOrderProcessByID(
        params.jobOrderProcessId
      ).subscribe((res: any) => {
        this.item = res;
        if (this.item.isLast) {
          this.radioItems = ['入库'];
          this.currentSelectedItem = '入库';
        }
        this.isStart = this.item.isStart == 'true';
        this.isFinished = this.item.isFinished == 'true';
        this.numberItems = [
          {
            num: this.item.productionQuantity,
            text: '计划数',
            color: 'default',
          },
          { num: this.item.reportedAmount, text: '已报工数', color: 'default' },
          {
            num: this.item.productionQuantity - this.item.qualifiedAmount,
            text: '剩余数',
            color: 'default',
          },
          {
            num: this.item.productionQuantity - this.item.qualifiedAmount,
            text: '可报工数',
            color: 'default',
          },
          {
            num: this.item.qualifiedAmount || 0,
            text: '合格数',
            color: 'rgb(0, 208, 143)',
          },
          {
            num: this.item.unqualifiedAmount || 0,
            text: '不合格数',
            color: 'rgb(255, 65, 54)',
          },
          {
            num: this.item.scrapAmount || 0,
            text: '报废数',
            color: 'rgb(255, 134, 32)',
          },
          {
            num: this.item.repairingAmount || 0,
            text: '维修中',
            color: 'rgb(163, 167, 179)',
          },
        ];
        if(this.item.isInspection||this.item.isFirstInspection&&this.item.reportProcessHistories.length==0){
          this.normalInputDisabled = true;
          this.inspectionInputDisabled = false;
          this.selectedInput = 'pendingInspectionQuantity'
        }else{
          this.inspectionInputDisabled = true;
          this.normalInputDisabled = false;
          this.selectedInput = 'reportedAmount'
        }
      });
    });

  }
  selectFooterItem(item: FooterItems) {
    this.selectedFooterItem = item;
  }
  Start() {
    this.JobOrderService.StartProcess(this.item.jobOrderProcessId).subscribe(
      (res: any) => {
        this.showToast('success', '成功', '开工成功');
        this.JobOrderService.GetJobOrderProcessByID(
          this.jobOrderProcessId
        ).subscribe((res: any) => {
          this.item = res;
        });
      },
      (error) => {
        if (error.status == 404) {
          this.showToast('error', '失败', '服务器连接失败');
        } else {
          this.showToast('error', '失败', error.error);
        }
      }
    );
  }
  onItemClick(item: string): void {
    if (item !== 'del') {
      if (this[this.selectedInput] == null) {
        this[this.selectedInput] = item;
      } else {
        this[this.selectedInput] += item;
      }
    } else {
      // 处理删除键的逻辑，例如删除输入框的最后一个字符
      this[this.selectedInput] = this[this.selectedInput].slice(0, -1);
    }
  }
  end(dialogtype?: string) {
    let data = {
      display: false,
      jobOrderId: this.item.jobOrderId,
      processNumber: this.item.processNumber,
      processId: this.item.processId,
    };
    const results = this.DialogService.open({
      data: data,
      title: '报工',
      content: '确认报工？',
      width: '300px',
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (
              (this.reportedAmount && this.reportedAmount > 0) ||
              (this.unqualifiedAmount && this.unqualifiedAmount > 0) ||
              (this.scrapAmount && this.scrapAmount > 0) ||
              (this.pendingInspectionQuantity && this.pendingInspectionQuantity > 0)
            ) {
              if (!this.item.isLast) {
                if(!this.inspectionInputDisabled){
                  this.EncodeRulesService.GenerateWarehouseCodeRule(
                    '生产质检单',
                    '生产质检单'
                  ).subscribe((res) => {
                    this.productionInspectionOrderNum = res;
                  });
                }
                  this.JobOrderService.ReportProcess({
                    jobOrderProcessId: Number(this.item.jobOrderProcessId),
                    pendingInspectionQuantity: this.pendingInspectionQuantity,
                    qualifiedAmount: Number(this.reportedAmount),
                    unqualifiedAmount: Number(this.unqualifiedAmount),
                    scrapAmount: Number(this.scrapAmount),
                    reportNote: this.item.reportNote || '',
                    employeeCode: this.employeeCode,
                    productionInspectionOrderNum: this.productionInspectionOrderNum,
                  }).subscribe(
                    (res: any) => {
                      setTimeout(() => {
                        this.router.navigate(['/opterator-tasks']);
                      }, 1000);
                      results.modalInstance.hide();
                      this.showToast('success', '成功', '报工成功');
                      this.JobOrderService.GetJobOrderProcessByID(
                        this.jobOrderProcessId
                      ).subscribe((res: any) => {
                        this.item = res;
                        this.numberItems = [
                          {
                            num: this.item.productionQuantity,
                            text: '计划数',
                            color: 'default',
                          },
                          {
                            num: this.item.reportedAmount,
                            text: '已报工数',
                            color: 'default',
                          },
                          {
                            num:
                              this.item.productionQuantity -
                              this.item.qualifiedAmount,
                            text: '剩余数',
                            color: 'default',
                          },
                          {
                            num:
                              this.item.productionQuantity -
                              this.item.qualifiedAmount,
                            text: '可报工数',
                            color: 'default',
                          },
                          {
                            num: this.item.qualifiedAmount || 0,
                            text: '合格数',
                            color: 'rgb(0, 208, 143)',
                          },
                          {
                            num: this.item.unqualifiedAmount || 0,
                            text: '不合格数',
                            color: 'rgb(255, 65, 54)',
                          },
                          {
                            num: this.item.scrapAmount || 0,
                            text: '报废数',
                            color: 'rgb(255, 134, 32)',
                          },
                          {
                            num: this.item.repairingAmount || 0,
                            text: '维修中',
                            color: 'rgb(163, 167, 179)',
                          },
                        ];
                        this.item = {
                          reportNote: '',
                        };
                        this.reportedAmount = null;
                        this.unqualifiedAmount = null;
                        this.scrapAmount = null;
                        results.modalInstance.hide();
                      });
                    },
                    (error) => {
                      if (error.status == 404) {
                        this.showToast('error', '失败', '服务器连接失败');
                      } else {
                        this.showToast('error', '失败', error.error);
                      }
                    }
                  );


              } else if (this.item.isLast) {
                this.EncodeRulesService.GenerateWarehouseCodeRule(
                  '生产入库单',
                  '生产入库单'
                ).subscribe((res: any) => {
                  if(!this.inspectionInputDisabled){
                    this.EncodeRulesService.GenerateWarehouseCodeRule(
                      '生产质检单',
                      '生产质检单'
                    ).subscribe((data) => {
                      this.productionInspectionOrderNum = data;
                      this.JobOrderService.OverReportProcess({
                        jobOrderProcessId: this.item.jobOrderProcessId,
                        pendingInspectionQuantity: Number(this.pendingInspectionQuantity),
                        productionInspectionOrderNum: data,
                        qualifiedAmount: Number(this.reportedAmount),
                        unqualifiedAmount: Number(this.unqualifiedAmount),
                        scrapAmount: Number(this.scrapAmount),
                        reportNote: '',
                        employeeCode: this.employeeCode,
                        productionWarehousingNum: res,
                        note: '',
                      }).subscribe(
                        (res: any) => {
                          this.showToast('success', '成功', '报工成功');
                          setTimeout(() => {
                            this.router.navigate(['/opterator-tasks']);
                          }, 1000);
                          results.modalInstance.hide();
                          // this.JobOrderService.GetJobOrderProcess(
                          //   this.item.jobOrderNum,
                          //   this.item.processNum.subscribe((res: any) => {
                          //     this.item = res.items[0];

                          //     this.numberItems = [
                          //       {
                          //         num: this.item.productionQuantity,
                          //         text: '计划数',
                          //         color: 'default',
                          //       },
                          //       {
                          //         num: this.item.reportedAmount,
                          //         text: '已报工数',
                          //         color: 'default',
                          //       },
                          //       {
                          //         num:
                          //           this.item.productionQuantity -
                          //           this.item.qualifiedAmount,
                          //         text: '剩余数',
                          //         color: 'default',
                          //       },
                          //       {
                          //         num:
                          //           this.item.productionQuantity -
                          //           this.item.qualifiedAmount,
                          //         text: '可报工数',
                          //         color: 'default',
                          //       },
                          //       {
                          //         num: this.item.qualifiedAmount || 0,
                          //         text: '合格数',
                          //         color: 'rgb(0, 208, 143)',
                          //       },
                          //       {
                          //         num: this.item.unqualifiedAmount || 0,
                          //         text: '不合格数',
                          //         color: 'rgb(255, 65, 54)',
                          //       },
                          //       {
                          //         num: this.item.scrapAmount || 0,
                          //         text: '报废数',
                          //         color: 'rgb(255, 134, 32)',
                          //       },
                          //       {
                          //         num: this.item.repairingAmount || 0,
                          //         text: '维修中',
                          //         color: 'rgb(163, 167, 179)',
                          //       },
                          //     ];
                          //     this.item = {
                          //       reportNote: '',
                          //     };
                          //     this.reportedAmount = null;
                          //     this.unqualifiedAmount = null;
                          //     this.scrapAmount = null;
                          //     results.modalInstance.hide();

                          //   })
                          // );
                        },
                        (error) => {
                          if (error.status == 404) {
                            this.showToast('error', '失败', '服务器连接失败');
                          } else {
                            this.showToast('error', '失败', error.error);
                          }
                        }
                      );
                    });
                  }else{
                    this.JobOrderService.OverReportProcess({
                      jobOrderProcessId: this.item.jobOrderProcessId,
                      pendingInspectionQuantity: Number(this.pendingInspectionQuantity),
                      productionInspectionOrderNum: "",
                      qualifiedAmount: Number(this.reportedAmount),
                      unqualifiedAmount: Number(this.unqualifiedAmount),
                      scrapAmount: Number(this.scrapAmount),
                      reportNote: '',
                      employeeCode: this.employeeCode,
                      productionWarehousingNum: res,
                      note: '',
                    }).subscribe(
                      (res: any) => {
                        this.showToast('success', '成功', '报工成功');
                        setTimeout(() => {
                          this.router.navigate(['/opterator-tasks']);
                        }, 1000);
                        results.modalInstance.hide();
                        // this.JobOrderService.GetJobOrderProcess(
                        //   this.item.jobOrderNum,
                        //   this.item.processNum.subscribe((res: any) => {
                        //     this.item = res.items[0];

                        //     this.numberItems = [
                        //       {
                        //         num: this.item.productionQuantity,
                        //         text: '计划数',
                        //         color: 'default',
                        //       },
                        //       {
                        //         num: this.item.reportedAmount,
                        //         text: '已报工数',
                        //         color: 'default',
                        //       },
                        //       {
                        //         num:
                        //           this.item.productionQuantity -
                        //           this.item.qualifiedAmount,
                        //         text: '剩余数',
                        //         color: 'default',
                        //       },
                        //       {
                        //         num:
                        //           this.item.productionQuantity -
                        //           this.item.qualifiedAmount,
                        //         text: '可报工数',
                        //         color: 'default',
                        //       },
                        //       {
                        //         num: this.item.qualifiedAmount || 0,
                        //         text: '合格数',
                        //         color: 'rgb(0, 208, 143)',
                        //       },
                        //       {
                        //         num: this.item.unqualifiedAmount || 0,
                        //         text: '不合格数',
                        //         color: 'rgb(255, 65, 54)',
                        //       },
                        //       {
                        //         num: this.item.scrapAmount || 0,
                        //         text: '报废数',
                        //         color: 'rgb(255, 134, 32)',
                        //       },
                        //       {
                        //         num: this.item.repairingAmount || 0,
                        //         text: '维修中',
                        //         color: 'rgb(163, 167, 179)',
                        //       },
                        //     ];
                        //     this.item = {
                        //       reportNote: '',
                        //     };
                        //     this.reportedAmount = null;
                        //     this.unqualifiedAmount = null;
                        //     this.scrapAmount = null;
                        //     results.modalInstance.hide();

                        //   })
                        // );
                      },
                      (error) => {
                        if (error.status == 404) {
                          this.showToast('error', '失败', '服务器连接失败');
                        } else {
                          this.showToast('error', '失败', error.error);
                        }
                      }
                    );
                  }
                });
              }
            }else{
              this.showToast('error', '失败', '报工数量不能为0');
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  cancel() {
    this.router.navigate(['/opterator-tasks']);
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  } //提示框
  paused(dialogtype?: string) {
    let data = {
      display: false,
      jobOrderId: this.item.jobOrderId,
      processNumber: this.item.processNumber,
      processId: this.item.processId,
    };
    const results = this.DialogService.open({
      data: data,
      title: '任务暂停',
      maxHeight: '130px',
      content: PausedComponent,
      dialogtype: dialogtype,
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.pauseInfo.pauseReason) {
              this.JobOrderService.SuspendProcess(
                this.item.jobOrderProcessId,
                results.modalContentInstance.pauseInfo.pauseReason,
                results.modalContentInstance.pauseInfo.note
              ).subscribe(
                (res: any) => {
                  this.showToast('success', '成功', '暂停成功');
                  this.JobOrderService.GetJobOrderProcessByID(
                    this.jobOrderProcessId
                  ).subscribe((res: any) => {
                    this.item = res;
                  });
                },
                (error) => {
                  if (error.status == 404) {
                    this.showToast('error', '失败', '服务器连接失败');
                  } else {
                    this.showToast('error', '失败', error.error);
                  }
                }
              );
              results.modalInstance.hide();
            } else {
              data.display = true;
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  pausedBefore() {
    if (this.item.isStart && !this.item.isFinished) {
      this.paused();
    } else {
      this.showToast('error', '失败', '工序未开工或已完工');
    }
  }
  restore() {
    this.JobOrderService.ContinueProcess(this.item.jobOrderProcessId).subscribe(
      (res: any) => {
        this.showToast('success', '成功', '恢复成功');
        this.JobOrderService.GetJobOrderProcessByID(
          this.jobOrderProcessId
        ).subscribe((res: any) => {
          this.item = res;
        });
      },
      (error) => {
        if (error.status == 404) {
          this.showToast('error', '失败', '服务器连接失败');
        } else {
          this.showToast('error', '失败', error.error);
        }
      }
    );
  }
  onInputClick(inputName: string): void {
    this.selectedInput = inputName;
  }
  radioChange($event: any) {
    if ($event == '入库') {
      this.item.isLast = true;
    } else {
      this.item.isLast = false;
    }
  }
  reportHistories(dialogtype?: string) {
    const results = this.DialogService.open({
      title: '报工历史',
      data: {
        data: {
          JobOrderNum: this.item.jobOrderNum,
          ProcessNum: this.item.processNum,
          PageNumber: 1,
          PageSize: 20,
        },
        title: '任务报工记录',
      },
      content: ReportHistoriesComponent,
      dialogtype: dialogtype,
      width: '900px',
      onClose: () => {},
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
}
